package com.zbkj.crmeb.store.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.utils.RedisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.PriceUtil;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.store.dao.ExhibitApplicationDao;
import com.zbkj.crmeb.store.dao.HomeActivityDao;
import com.zbkj.crmeb.store.model.CustomsRecord;
import com.zbkj.crmeb.store.model.ExhibitApplication;
import com.zbkj.crmeb.store.model.HomeActivity;
import com.zbkj.crmeb.store.model.StoreProductMer;
import com.zbkj.crmeb.store.request.CustomsRecordSearchRequest;
import com.zbkj.crmeb.store.request.ExhibitApplicationSearchRequest;
import com.zbkj.crmeb.store.response.CustomsRecordResponse;
import com.zbkj.crmeb.store.response.ExhibitApplicationResponse;
import com.zbkj.crmeb.store.service.CustomsRecordService;
import com.zbkj.crmeb.store.service.ExhibitApplicationService;
import com.zbkj.crmeb.store.service.HomeActivityService;
import com.zbkj.crmeb.user.service.UserService;

/**
* @author Mr.Zhang
* @description StoreProductServiceImpl 接口实现
* @date 2020-05-27
*/
@Slf4j
@Service
public class ExhibitApplicationServiceImpl extends ServiceImpl<ExhibitApplicationDao, ExhibitApplication> implements ExhibitApplicationService {
    @Autowired
    PriceUtil priceUtil;
    @Resource
    private ExhibitApplicationDao exhibitApplicationDao;
    @Resource
    private HomeActivityService homeActivityService;
    @Resource
    private HomeActivityDao homeActivityDao;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(ExhibitApplicationServiceImpl.class);

    /**
     * 展会报名列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @author Mr.Zhang
     * @since 2020-05-27
     * @return List<StoreProduct>
     */
    @Override
    public PageInfo<ExhibitApplicationResponse> getList(ExhibitApplicationSearchRequest request, PageParamRequest pageParamRequest) {
        //条件查询
        Page<ExhibitApplication> exhibitApplicationPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<ExhibitApplicationResponse> exhibitApplications = exhibitApplicationDao.queryApplicationList(request);
        if(CollectionUtils.isEmpty(exhibitApplications)) {
            return CommonPage.copyPageInfo(exhibitApplicationPage, new ArrayList<>());
        }
        List<Integer> activityIds = exhibitApplications.stream().map(ExhibitApplicationResponse::getActivityId).distinct().collect(Collectors.toList());

        Map<Integer,HomeActivity> activityMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(activityIds)) {
            List<HomeActivity> homeActivitys = homeActivityDao.selectList(Wrappers.<HomeActivity>lambdaQuery()
                    .in(HomeActivity :: getId, activityIds)
            );
            Map<Integer,HomeActivity> activityMap1 = homeActivitys.stream().collect(Collectors.toMap(HomeActivity::getId, s -> s, (v1, v2) -> v1));
            activityMap.putAll(activityMap1);
        }

        List<ExhibitApplicationResponse> responses = exhibitApplications.stream().map(item -> {
            if(!StringUtils.isEmpty(item.getGender())){
                item.setGender("1".equals(item.getGender()) ? "男" : "女");
            }
            Integer activityId = item.getActivityId();
            if(null != activityId && 0 != activityId){
                HomeActivity activity = activityMap.get(activityId);
                if(null != activity){
                    item.setActivityName(activity.getName());
                }
            }
            return item;
        }).collect(Collectors.toList());
        return CommonPage.copyPageInfo(exhibitApplicationPage, responses);
    }

    /**
     * 展会报名新增
     * @param exhibitApplication
     * @return
     */
    @Override
    public String saveExhibitApplication(ExhibitApplication exhibitApplication, Integer merId) {
        if (merId != null && merId != 0) {
            exhibitApplication.setMerId(merId);
        }
        Integer userId = userService.getUserIdException();
        if (userId != null && userId != 0) {
            exhibitApplication.setCreateUserUid(String.valueOf(userId));
            // 判断累计场次
            int count = this.count(Wrappers.<ExhibitApplication>lambdaQuery().eq(ExhibitApplication::getActivityTime, exhibitApplication.getActivityTime()));
            if (count>=50){
                return "该活动场次已满，请选择其他场次报名！";
            }
            Integer activityId = exhibitApplication.getActivityId();
            if (null == activityId) {
                activityId = 0;
            }
            ExhibitApplication exist = this.getOne(Wrappers.<ExhibitApplication>lambdaQuery()
                    .eq(ExhibitApplication :: getCreateUserUid, String.valueOf(userId))
                    .eq(ExhibitApplication :: getActivityId, String.valueOf(activityId))
                    .last("limit 1"));

            String key = "exhibit_application_" + userId;
            if(exist != null) {
//                try {
//                    String value = redisUtil.get(key).toString();
//                    log.info("缓存key：{}，value：{}", key, value);
//                    if (StringUtils.isNotEmpty(value)) {
//                        Integer intValue = Integer.valueOf(value);
//                        intValue--;
//                        if (intValue > 0) {
//                            redisUtil.set(key, String.valueOf(intValue), Constants.EXHIBIT_APPLICATION_EXPRESS_MINUTES, TimeUnit.MINUTES);
//                        }else {
//                            return "您已更新报名三次，如需再次更新，请联系管理员！";
//                        }
//                    }else{
//                        redisUtil.set(key, "2", Constants.EXHIBIT_APPLICATION_EXPRESS_MINUTES, TimeUnit.MINUTES);
//                    }
//                }catch (Exception e){
//                    log.error("缓存{}更新失败！",key);
//                }
                // 删除原数据
                this.removeById(exist.getId());

            }
//            else {
//                redisUtil.set(key, "3", Constants.EXHIBIT_APPLICATION_EXPRESS_MINUTES, TimeUnit.MINUTES);
//            }
        }
        if(CollectionUtils.isNotEmpty(exhibitApplication.getBusinessNameList())){
            exhibitApplication.setBusinessName(String.join("，", exhibitApplication.getBusinessNameList()));
        }
        if(CollectionUtils.isNotEmpty(exhibitApplication.getPreferenceNameList())){
            exhibitApplication.setPreferenceName(String.join("，", exhibitApplication.getPreferenceNameList()));
        }
        if(CollectionUtils.isNotEmpty(exhibitApplication.getPurchaseChannelList())){
            exhibitApplication.setPurchaseChannel(String.join("，", exhibitApplication.getPurchaseChannelList()));
        }
        boolean b = this.save(exhibitApplication);

        return b ? null : "保存失败";
    }

}
